package cn.dxs.adt.utils;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.content.pm.ResolveInfo;
import android.content.pm.ServiceInfo;
import android.net.Uri;
import android.provider.Settings;
import android.text.TextUtils;

import java.io.File;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import cn.dxs.adt.bean.AppInfo;

public class Util {
    private static DecimalFormat df = new DecimalFormat("0.00");//格式化小数

    /**
     * 新闻创建时间
     *
     * @param date
     * @return
     */
    public static String getCreateTime(Date date) {
        return getCreateTime(date, "yyyy-MM-dd");
    }

    /**
     * 新闻创建时间
     *
     * @param date
     * @param pattern 格式："yyyy-MM-dd HH:mm:ss"
     * @return
     */
    public static String getCreateTime(Date date, String pattern) {
        if (date == null) {
            return "";
        }
        SimpleDateFormat formatter = new SimpleDateFormat(pattern);
        return formatter.format(date);
    }

    /**
     * 文件最后修改时间（格式：2020-03-24 17:28:38）
     *
     * @param time
     * @return
     */
    public static String getLastModifiedTime(long time) {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        cal.setTimeInMillis(time);
        return formatter.format(cal.getTime());
    }

    public static String getStub(String applicationName) {
        String stub = "未加固";
        if ("com.stub.StubApp".equals(applicationName)) {
            stub = "360加固";
        } else if (applicationName != null && applicationName.endsWith(".MyWrapperProxyApplication")) {
            stub = "腾讯御安全";
        } else {
            stub = "未加固";
        }
        return stub;
    }

    public static String getFileSize(String filePath) {
        long length = new File(filePath).length();
        if (length >= 1048576) {
            return df.format((float) length / 1048576) + "MB";
        } else if (length >= 1024) {
            return df.format((float) length / 1024) + "KB";
        } else if (length < 1024) {
            return length + "B";
        } else {
            return "0KB";
        }
    }

    /**
     * 获取一个运行耗时
     *
     * @param start
     * @return
     */
    public static String getCountdown(long start) {
        // 按照传入的格式生成一个simpledateformate对象
        long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
        long nh = 1000 * 60 * 60;// 一小时的毫秒数
        long nm = 1000 * 60;// 一分钟的毫秒数
        long ns = 1000;// 一秒钟的毫秒数

        // 获得两个时间的毫秒时间差异
        long diff = System.currentTimeMillis() - start;
        long day = diff / nd;// 计算差多少天
        long hour = diff % nd / nh;// 计算差多少小时
        long min = diff % nd % nh / nm;// 计算差多少分钟
        long second = diff % nd % nh % nm / ns;// 计算差多少秒
        long millisecond = diff % nd % nh % nm % ns;// 计算差多少毫秒

        // 输出结果
        StringBuilder sb = new StringBuilder();
        if (day != 0) {
            sb.append(day).append("天");
        }
        if (hour != 0) {
            sb.append(hour).append("时");
        }
        if (min != 0) {
            sb.append(min).append("分");
        }
        if (second != 0) {
            sb.append(second).append("秒");
        }
        if (millisecond != 0) {
            sb.append(millisecond).append("毫秒");
        }
        return sb.toString();
    }

    /**
     * 启动指定包名的APP
     *
     * @param context
     * @param packageName
     */
    public static void startAPP(Context context, String packageName) {
        Intent LaunchIntent = context.getPackageManager().getLaunchIntentForPackage(packageName);
        context.startActivity(LaunchIntent);
    }

    /**
     * 跳转到应用详情界面
     *
     * @param context
     * @param packageName
     */
    public static void gotoAppDetailIntent(Context context, String packageName) {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + packageName));
        context.startActivity(intent);
    }

    /**
     * 安装一个apk文件
     *
     * @param context
     * @param uriFile
     */
    public static void install(Context context, File uriFile) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(uriFile), "application/vnd.android.package-archive");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    /**
     * 卸载一个app
     *
     * @param context
     * @param packageName
     */
    public static void uninstall(Context context, String packageName) {
        //通过程序的包名创建URI
        Uri packageURI = Uri.parse("package:" + packageName);
        //创建Intent意图
        Intent intent = new Intent(Intent.ACTION_DELETE, packageURI);
        //执行卸载程序
        context.startActivity(intent);
    }

    public static List<AppInfo> scanInstallApp(Context mContext) {
        List<AppInfo> appInfos = new ArrayList<>();
        PackageManager pm = mContext.getPackageManager(); // 获得PackageManager对象
        List<ApplicationInfo> listAppcations = pm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
        Collections.sort(listAppcations, new ApplicationInfo.DisplayNameComparator(pm));// 字典排序
        for (ApplicationInfo app : listAppcations) {
            if ((app.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) {//非系统程序
                appInfos.add(getAppInfo(app, pm));
            }
            //本来是系统程序，被用户手动更新后，该系统程序也成为第三方应用程序了
            else if ((app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
                appInfos.add(getAppInfo(app, pm));
            }
        }
        return appInfos;
    }

    /**
     * 构造一个AppInfo对象 ，并赋值
     */
    private static AppInfo getAppInfo(ApplicationInfo app, PackageManager pm) {
        AppInfo appInfo = new AppInfo();
        appInfo.appName = pm.getApplicationLabel(app).toString();//应用名称
        appInfo.appIcon = app.loadIcon(pm);//应用icon
        appInfo.packageName = app.packageName;//应用包名，用来卸载
        File file = new File(app.sourceDir);
        float size = file.length();
        DecimalFormat df = new DecimalFormat("#.00");
        appInfo.apkSize = df.format(size / (1024 * 1024)) + "M";//应用大小，M单位，保留两位小数
        PackageInfo packageInfo = null;
        try {
            packageInfo = pm.getPackageInfo(app.packageName, 0);
//            long lastUpdateTime = packageInfo.lastUpdateTime;//应用最近一次更新时间
//            appInfo.lastUpdateTime = TimeUtil.time2Ago(lastUpdateTime);//将毫秒时间对比当前时间转换为多久以前
            appInfo.lastUpdateTime = getLastModifiedTime(packageInfo.lastUpdateTime);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return appInfo;
    }

    public static String getMainEntryClassName(PackageManager packageManager, String packageName) {
        Intent intent = new Intent(Intent.ACTION_MAIN, null);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(intent, 0);
        for (int j = 0; j < resolveInfo.size(); j++) {
            if (packageName.equals(resolveInfo.get(j).activityInfo.packageName)) {
                return resolveInfo.get(j).activityInfo.name;
            }
        }
        return null;
    }

    public static List<String> getRequestedPermissionInfo(PackageManager packageManager, String apkPath) {
        String[] requestedPermissions = packageManager.getPackageArchiveInfo(apkPath, PackageManager.GET_PERMISSIONS).requestedPermissions;
        if (requestedPermissions != null) {
            return Arrays.asList(requestedPermissions);
        }
        return null;
    }

    public static List<String> getActivityInfo(PackageManager packageManager, String apkPath) {
        ActivityInfo[] activities = packageManager.getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES).activities;
        if (activities != null) {
            List<String> list = new ArrayList<>();
            for (ActivityInfo activity : activities) {
                list.add(activity.name);
            }
            return list;
        }
        return null;
    }

    public static List<String> getServiceInfo(PackageManager packageManager, String apkPath) {
        ServiceInfo[] services = packageManager.getPackageArchiveInfo(apkPath, PackageManager.GET_SERVICES).services;
        if (services != null) {
            List<String> list = new ArrayList<>();
            for (ServiceInfo service : services) {
                list.add(service.name);
            }
            return list;
        }
        return null;
    }

    public static List<String> getReceiverInfo(PackageManager packageManager, String apkPath) {
        ActivityInfo[] receivers = packageManager.getPackageArchiveInfo(apkPath, PackageManager.GET_RECEIVERS).receivers;
        if (receivers != null) {
            List<String> list = new ArrayList<>();
            for (ActivityInfo receiver : receivers) {
                list.add(receiver.name);
            }
            return list;
        }
        return null;
    }

    public static List<String> getProviderInfo(PackageManager packageManager, String apkPath) {
        ProviderInfo[] providers = packageManager.getPackageArchiveInfo(apkPath, PackageManager.GET_PROVIDERS).providers;
        if (providers != null) {
            List<String> list = new ArrayList<>();
            for (ProviderInfo provider : providers) {
                list.add(provider.name);
            }
            return list;
        }
        return null;
    }


}
